package com.quaidi.smartlocker.service;

import com.quaidi.smartlocker.entity.SysAdmin;
import com.quaidi.smartlocker.enums.UserRole;
import com.quaidi.smartlocker.mapper.SysAdminMapper;
import com.quaidi.smartlocker.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 用户服务类
 * 
 * @author QuaiDi
 * @since 2025-08-26
 */
@Service
public class UserService {
    
    @Autowired
    private SysAdminMapper sysAdminMapper;
    
    private static final String SESSION_USER_ROLE = "userRole";
    private static final String SESSION_ADMIN_ID = "adminId";
    private static final String DEFAULT_ADMIN_PASSWORD = "admin123"; // 兼容旧系统
    
    /**
     * 用户登录
     * 
     * @param username 用户名（可为空，默认为admin）
     * @param password 密码
     * @param session HTTP会话
     * @param request HTTP请求
     * @return 用户角色
     * @throws RuntimeException 密码错误时抛出异常
     */
    public UserRole login(String username, String password, HttpSession session, HttpServletRequest request) {
        // 检查密码是否为空
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        
        // 默认用户名为admin
        if (username == null || username.trim().isEmpty()) {
            username = "admin";
        }
        
        // 从数据库查询管理员
        SysAdmin admin = sysAdminMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SysAdmin>()
                .eq("username", username)
                .eq("status", 1)
        );
        
        if (admin == null) {
            // 兼容性处理：如果数据库中没有管理员，使用默认密码
            if (DEFAULT_ADMIN_PASSWORD.equals(password)) {
                UserRole role = UserRole.ADMIN;
                session.setAttribute(SESSION_USER_ROLE, role);
                return role;
            } else {
                throw new RuntimeException("管理员不存在或已被禁用");
            }
        }
        
        // 验证密码
        boolean passwordValid = false;
        
        // 先尝试使用盐值加密验证
        if (admin.getSalt() != null && !admin.getSalt().isEmpty()) {
            passwordValid = PasswordUtil.verifyPassword(password, admin.getSalt(), admin.getPassword());
        } else {
            // 如果没有盐值，尝试简单加密验证（兼容旧数据）
            passwordValid = PasswordUtil.verifySimplePassword(password, admin.getPassword());
        }
        
        if (!passwordValid) {
            throw new RuntimeException("管理员密码错误");
        }
        
        // 更新登录信息
        admin.setLastLoginTime(LocalDateTime.now());
        admin.setLastLoginIp(getClientIp(request));
        admin.setLoginCount((admin.getLoginCount() == null ? 0 : admin.getLoginCount()) + 1);
        sysAdminMapper.updateById(admin);
        
        // 设置会话信息
        UserRole role = UserRole.ADMIN;
        session.setAttribute(SESSION_USER_ROLE, role);
        session.setAttribute(SESSION_ADMIN_ID, admin.getId());
        
        return role;
    }
    
    /**
     * 获取当前用户角色
     * 
     * @param session HTTP会话
     * @return 用户角色
     */
    public UserRole getCurrentUserRole(HttpSession session) {
        UserRole role = (UserRole) session.getAttribute(SESSION_USER_ROLE);
        return role != null ? role : UserRole.USER; // 默认为普通用户
    }
    
    /**
     * 用户登出
     * 
     * @param session HTTP会话
     */
    public void logout(HttpSession session) {
        session.removeAttribute(SESSION_USER_ROLE);
    }
    
    /**
     * 检查用户是否有指定角色权限
     * 
     * @param session HTTP会话
     * @param requiredRole 需要的角色
     * @return 是否有权限
     */
    public boolean hasRole(HttpSession session, UserRole requiredRole) {
        UserRole currentRole = getCurrentUserRole(session);
        
        // 管理员拥有所有权限
        if (currentRole == UserRole.ADMIN) {
            return true;
        }
        
        // 普通用户只有USER权限
        return currentRole == requiredRole;
    }
    
    /**
     * 获取客户端IP地址
     * 
     * @param request HTTP请求
     * @return IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 处理多个IP的情况，取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
}